package logger

import (
    "fmt"
    "log"
    "os"
    "sync"
)

var (
    std  = log.New(os.Stdout, "[dl] ", log.LstdFlags|log.Lmicroseconds)
    mu   sync.RWMutex
    subs = make([]chan string, 0)
)

func Init() {}

func broadcast(msg string) {
    mu.RLock()
    defer mu.RUnlock()
    for _, ch := range subs {
        select {
        case ch <- msg:
        default:
            // drop if slow consumer
        }
    }
}

func Subscribe() chan string {
    mu.Lock()
    defer mu.Unlock()
    ch := make(chan string, 200)
    subs = append(subs, ch)
    return ch
}

func Unsubscribe(ch chan string) {
    mu.Lock()
    defer mu.Unlock()
    for i, c := range subs {
        if c == ch {
            subs = append(subs[:i], subs[i+1:]...)
            close(c)
            break
        }
    }
}

func Infof(format string, v ...any)  { msg := fmt.Sprintf("INFO "+format, v...); std.Println(msg); broadcast(msg) }
func Errorf(format string, v ...any) { msg := fmt.Sprintf("ERROR "+format, v...); std.Println(msg); broadcast(msg) }
func Warnf(format string, v ...any)  { msg := fmt.Sprintf("WARN "+format, v...); std.Println(msg); broadcast(msg) }
